package com.ruge.user.controller;

import com.ruge.core.response.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: ruge-cloud
 * @description:
 * @author: ruge.wu
 * @create: 2022-01-03 20:57
 **/
@Slf4j
@RestController
@RequestMapping("oauth")
@Api(tags = "【oauth 接口】", value = "【oauth 接口】")
public class OAuthController {
    @Resource
    private TokenEndpoint tokenEndpoint;

    private HttpRequest request;


    @PostMapping("token")
    @ApiOperation(value = "【oauth】  获取token",notes = "{\n" +
            "    \"username\":\"13298899809\",\n" +
            "    \"password\":\"123456\",\n" +
            "    \"grant_type\":\"password\"\n" +
            "}")
    public Response postAccessToken(Principal principal, @RequestParam Map<String, String> parameters)
            throws HttpRequestMethodNotSupportedException {
        return custom(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    }


    /**
     * 自定义 Token 返回对象
     *
     * @param accessToken
     * @return
     */
    private Response custom(OAuth2AccessToken accessToken) {
        DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) accessToken;
        Map<String, Object> data = new LinkedHashMap(token.getAdditionalInformation());
        data.put("accessToken", token.getValue());
        data.put("expireIn", token.getExpiresIn());
        data.put("scopes", token.getScope());
        if (token.getRefreshToken() != null) {
            data.put("refreshToken", token.getRefreshToken().getValue());
        }
        return Response.create(data);
    }
}
